package initialize

import (
	"fmt"

	"github.com/robfig/cron/v3"

	"gitee.com/g-qs/gin-vue-admin/server/config"
	"gitee.com/g-qs/gin-vue-admin/server/global"
	"gitee.com/g-qs/gin-vue-admin/server/utils"
)

func Timer() {
	if global.GVA_CONFIG.Timer.Start {
		for i := range global.GVA_CONFIG.Timer.Detail {
			go func(detail config.Detail) {
				var option []cron.Option
				if global.GVA_CONFIG.Timer.WithSeconds {
					option = append(option, cron.WithSeconds())
				}
				_, err := global.GVA_Timer.AddTaskByFunc("ClearDB", global.GVA_CONFIG.Timer.Spec, func() {
					err := utils.ClearTable(global.GVA_DB, detail.TableName, detail.CompareField, detail.Interval)
					if err != nil {
						fmt.Println("timer error:", err)
					}
				}, "ClearDB", option...)
				if err != nil {
					fmt.Println("add timer error:", err)
				}
			}(global.GVA_CONFIG.Timer.Detail[i])
		}
	}
	go func() {
		_, err := global.GVA_Timer.AddTaskByFunc("CheckExpiredMembers", "0 1 * * *", func() {
			err := utils.CheckExpiredMembers(global.GVA_DB)
			if err != nil {
				fmt.Println("timer error:", err)
			}
		}, "CheckExpiredMembers")
		if err != nil {
			fmt.Println("add CheckExpiredMembers error:", err)
		}
		_, err = global.GVA_Timer.AddTaskByFunc("UpdateCountData", "42 * * * *", func() {
			err := utils.UpdateCountData(global.GVA_DB)
			if err != nil {
				fmt.Println("timer error:", err)
			}
		}, "UpdateCountData")
		if err != nil {
			fmt.Println("add UpdateCountData error:", err)
		}
	}()
}
